﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;

namespace makitRS.Core.Account
{
    public class OpenIDManager
    {

        #region Members

        private static OpenIdRelyingParty openid = new OpenIdRelyingParty();

        public static OpenIdRelyingParty OpenIDProv {
            get
            {
                return openid;
            }
        }

        #endregion


        #region Response

        public struct OpenIDResponseReturn
        {
            public bool ErrorOccured;
            public string ErrorMessage;

            public string UserName;

            public bool UnknownUser;
            public string UnknownUserClaimedID;
        }

        public static OpenIDResponseReturn parseResponse(IAuthenticationResponse response)
        {

            OpenIDResponseReturn toRet = new OpenIDResponseReturn();

            if (response != null)
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:

                        string id = response.ClaimedIdentifier.ToString();
                        id = id.Substring(id.IndexOf("id=")+3);

                        //TODO: Read from datasource 
                        if (id == "AItOawl8ZWOC51h-BHYRZBVKhgEAI-Yza-DeULE")
                        {
                            toRet.UserName = "makit";
                        }
                        else
                        {
                            toRet.UnknownUser = true;
                            toRet.UnknownUserClaimedID = id;
                        }

                        return toRet;

                    case AuthenticationStatus.Canceled:
                        toRet.ErrorMessage = "Canceled at Google";
                        return toRet;

                    case AuthenticationStatus.Failed:
                        toRet.ErrorOccured = true;
                        toRet.ErrorMessage = response.Exception.Message;
                        return toRet;
                }
            }

            toRet.ErrorOccured = true;
            toRet.ErrorMessage = "Unknown Reason";
            return toRet;

        }

        #endregion

    }
}
